<template>
  <div class="app-container">
    <div class="top-main">
    <el-form  class="top-form-fl" :model="param" label-width="auto" :inline="true">
      <el-form-item label="订单号">
        <el-input v-model.trim="param.orderNo" clearable placeholder="请输入订单号"> </el-input>
      </el-form-item>
      <el-form-item label="售箱城市">
        <city-select v-model="param.carryCityId" :selectCity="param.boxStartCity" @cityId="startCityId"
          @clear="param.carryCityId = null" style="width: 100%;"></city-select>
      </el-form-item>
      <el-form-item label="客户">
        <el-input v-model.trim="param.buyBoxCompanyName" clearable  placeholder="请输入"> </el-input>
      </el-form-item>
      <el-form-item label="结算币种">
        <el-select v-model="param.currency" clearable placeholder="请选择">
          <el-option v-for="item in param.payCurrencys" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="发票号">
        <el-input v-model.trim="param.invoiceNo" clearable  placeholder="请输入"> </el-input>
      </el-form-item>
      <el-form-item label="联系人">
        <el-input v-model.trim="param.contacts" clearable placeholder="请输入联系人"> </el-input>
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model.trim="param.tel" clearable placeholder="请输入联系电话"> </el-input>
      </el-form-item>
        <el-form-item label="预计提箱日期" style="width: 350px;">
        <el-date-picker v-model="param.planPickupDate" type="daterange" clearable range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="下单日期" style="width: 350px;">
        <el-date-picker v-model="param.createDate" type="daterange" clearable range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
    </el-form>
    <div class="top-from-fr">
        <el-button class="top-Search" @click="getTableData" type="primary">搜索</el-button>
        <el-button class="top-Refresh" @click="handleReSet">重置</el-button>
      </div>   
    </div>
    <cz-tages :bottomLine="true" :typeList="typeList" @handleTypeChange="handleTypeChange" style="float: left;"></cz-tages>
    <span style="margin-top: -40px;float: right;">
      <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有订单" placement="left">
        <template v-if="isSelectAll">
          <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
        </template>
        <template v-else>
            <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
        </template>
      </el-tooltip>
      <el-button size="small" @click="toExportBuyBoxPacking" plain>导出</el-button>
      <el-button type="primary" size="small" @click="batchDelete" plain>删除</el-button>
    </span>

    <Table ref="tableRef" v-bind="table" :allId="allId" :isAllCheck="isAllCheck" @pageChange="onTablePageChange" @showInfo="showInfo"
      @handleToRefund="handleToRefund" @handleShowContract="handleShowContract" @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
    </Table>

    <!-- 确认退款 -->
    <el-dialog v-model="param.dialogVisible" width="70%">
      <refundCard @close="handleClose" :rowData="rowData" :opr="'refundPitch'">
      </refundCard>
    </el-dialog>

    <!-- 订单申请协议 -->
    <el-dialog v-model="param.dialogContract" :with-header="false">
      <pdfViewer :url="param.contractUrl"></pdfViewer>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import pdfViewer from '@/components/pdf'
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
import citySelect from '@/components/citySelect'
import orderInfo from '@/store/modules/order'
import { downloadFile } from '@/utils/download'
import invoiceTemplate from '@/views/components/invoiceTemplate'
import refundCard from '@/views/components/order/refundCard'
import { getSellPurchaseBoxOrderPage, refundPurchaseBoxOrderById,exportBoxPurchaseBoxOrder,boxEastStatusCount ,deleteOrderByIds} from '@/api/boxDeal/boxBuy'
import { ElMessage , ElMessageBox} from 'element-plus';

import { computed, onMounted, onActivated, reactive, ref } from 'vue';
import { Plus, Delete, Edit, Message, Download,Document,Upload, Finished } from '@element-plus/icons-vue'
import { useRouter,useRoute } from 'vue-router';

const router = useRouter();

const param = reactive({
  payCurrencys: [{ label: '美元', value: 'USD' }, { label: '人民币', value: 'CNY' }], //美元:USD 人民币:CNY
  loading: false,
  pageNum: 1,
  pageSize: 10,
  stateFilter: { 2: '待确认', 3: '待签署', 10: '待开发票', 15: '未收', 20: '已收', 25: '待提', 30: '已提', 35: '已完成', 40: '已取消', 45: '待取消' },
  // stateColor: { 5: '#22A86D', 10: '#2158F3', 15: '#2158F3' },
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提(次新或者适货)', },
    { value: '5', label: '全新', },
  ],
  beginTotalRentQty: '',
  endTotalRentQty: '',
  boxBackCity: '',
  boxStartCity: '',
  startCityOptions: [],
  backCityOptions: [],
  contacts:'',
  tel:'',
  status:''
});

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'orderNo', key2: 'refundStatusName', colWidth: '220', title: '订单号', type: '<a>', command: 'showInfo', isCheck: true },
    { key: 'carryCityName', key2: 'carryCountryName', colWidth: '160', title: '售箱城市', type: 'twoRow', isCheck: true },
    { key: 'createTime', colWidth: '150', title: '下单日期', type: 'dateTime', isCheck: true },
    { key: 'planPickupDate', colWidth: '150', title: '预计提箱日期', type: 'date', isCheck: true },
    { key: 'boxType', colWidth: '100', title: '箱型', type: 'filter', filter: { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }, isCheck: true },
    { key: 'boxCondition', colWidth: '100', title: '箱况', type: 'filter', filter: { 5: '全新', 10: '次新', 15: '适货' }, isCheck: true },
    { key: 'boxQuantity', colWidth: '100', title: '箱量', type: 'text', isCheck: true },
    { key: 'amount', colWidth: '120', title: '订单金额', type: 'add', currency: 'currency', isCheck: true },
    { key: 'status', colWidth: '120', title: '订单状态', type: 'filter', filter: param.stateFilter, isCheck: true },
    { key: 'agentUserName', colWidth: '120', title: '联系人', type: 'text', isCheck: true },
    { key: 'agentUserTel',key2: 'agentUserAreaCode', colWidth: '150', title: '联系电话', type: 'mobileCode',isCheck: true },
    { key: 'invoiceNo', colWidth: '120', title: '发票号', type: '<a>', isCheck: true },
    {
      key: 'operate',
      colWidth: '120',
      title: '订单申请协议',
      type: 'operate',
      isCheck: true,
      buttons: [{
        icon: Document,
        command: 'handleShowContract',
        isShow: (row) => {
          return row.downloadUrl
        },
      },]
    },
    { key: 'buyBoxCompanyName', colWidth: '200', title: '客户', type: 'text', isCheck: true },
    {
      key: 'operate',
      colWidth: '150',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          // content: '确认退款',
          // icon: 'Edit',
          command: 'handleToRefund',
          name:'确认退款',
          isShow: (row: { refundStatus: string; }) => {
            return row.refundStatus == '5';
          },
        },
        // {
        //   // content: '联系客服',
        //   // icon: 'Edit',
        //   command: 'showInfo',
        //   name:'联系客服',
        //   isShow: (row: { status: string; }) => {
        //     return row.status != '5';
        //   },
        // },
      ]
    }
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});

// const typeList = computed(() => {//{ 2: '待确认',3: '待审核', 10: '待开发票', 15: '未收', 20: '已收', 25: '待提', 30: '已提', 35: '已完成', 40: '已取消' }, 
//   // const list = [{ id: 0, name: '全部' }, { id: 5, name: '待确认' }, { id: 10, name: '待开发票' }, { id: 15, name: '未收' }, { id: 20, name: '已收' }, { id: 25, name: '待提' }, { id: 30, name: '已提' }, { id: 35, name: '已完成' }, { id: 40, name: '已取消' }]
//   const list = [
//     { id: 0, name: '全部' },
//     { id: 2, name: '待确认' },
//     { id: 3, name: '待审核' },
//     { id: 10, name: '待开发票' },
//     { id: 15, name: '未收' },
//     { id: 20, name: '已收' },
//     { id: 25, name: '待提' },
//     { id: 30, name: '已提' },
//     { id: 35, name: '已完成' },
//     { id: 45, name: '待取消' },
//     { id: 40, name: '已取消' },
//   ]
//   return list
// })
const typeList = ref([
    { id: 0, name: '全部',num:0 },
    { id: 2, name: '待确认',num:0  },
    { id: 3, name: '待签署',num:0  },
    // { id: 10, name: '待开发票',num:0 },
    // { id: 15, name: '未收' ,num:0 },
    // { id: 20, name: '已收',num:0  },
    { id: 25, name: '待提',num:0  },
    { id: 30, name: '已提',num:0  },
    { id: 35, name: '已完成',num:0  },
    { id: 45, name: '待取消',num:0  },
    { id: 40, name: '已取消' ,num:0 },
])

function handleTypeChange(val: any) {
  // console.log(val)
  param.status = val
  getTableData()
  deselectAll()
}
function getTableData() {
  let data = {
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    carryCityId: param.boxStartCity|| null,
    // companyId: param.companyId,
    buyBoxCompanyName: param.buyBoxCompanyName?.toUpperCase(),
    currency: param.currency,
    invoiceNo: param.invoiceNo?.toUpperCase(),
    orderNo: param.orderNo?.toUpperCase(),
    status: param.status || null,
    contacts:param.contacts,
    tel: param.tel
  }
  if (param.createDate) {
    data.beginCreateDate = param.createDate[0]
    data.endCreateDate = param.createDate[1]
  }
  if (param.planPickupDate) {
    data.beginPlanPickupDate = param.planPickupDate[0]
    data.endPlanPickupDate = param.planPickupDate[1]
  }
  table.config.loading = true;
  // 获取列表数据
  getSellPurchaseBoxOrderPage(data).then(res => {
    const statusFilter = { 5: '确认退款中', 10: '已确认退款', 15: '待退款', 20: '已退款', } //5 - 待确认 10 - 已确认 15 - 待退款 20 - 已退款
    table.data = res.data.list;
    table.data.forEach(item => {
      if (item.refundStatus) {
        item.refundStatusName = statusFilter[item.refundStatus]
      }
    })
    table.config.total = res.data.total;
  });
  getboxEastStatusCount()
  table.config.loading = false;
}

// 查询各状态数量
async function getboxEastStatusCount(){
  let reqParam = {
    orderNo: param.orderNo,
    carryCityId: param.boxStartCity,
    beginPlanPickupDate:'',
    endPlanPickupDate:'',
    beginCreateDate:'',
    endCreateDate:'',
    buyBoxCompanyName: param.buyBoxCompanyName?.toUpperCase(),
    currency: param.payCurrency,
    invoiceNo: param.invoiceNo?.toUpperCase(),
    contacts:param.contacts,
    tel: param.tel
  }
  if (param.createDate) {
    reqParam.beginCreateDate = param.createDate[0]
    reqParam.endCreateDate = param.createDate[1]
  }
  if (param.planPickupDate) {
    reqParam.beginPlanPickupDate = param.planPickupDate[0]
    reqParam.endPlanPickupDate = param.planPickupDate[1]
  }

  await boxEastStatusCount(reqParam).then(res => { 
    if(res.code == '00000'){
      typeList.value.forEach(item => { 
        item.num = 0
        res.data.forEach(item1 => { 
          if(item.id == 0){ //全部
            item.num += item1.totalQty
          }else if(item.id == 2 && item1.status ==2){ //待确认
              item.num += item1.totalQty
          }else if(item.id == 3 && item1.status == 3){ //待审核
              item.num += item1.totalQty
          }else if(item.id == 5 && item1.status == 5){ //待开提箱单
              item.num += item1.totalQty
          }else if(item.id == 10 && item1.status == 10 ){ //待提
              item.num += item1.totalQty
          }else if(item.id == 15 && item1.status == 15){ //已提
              item.num += item1.totalQty
          }else if(item.id == 20 && item1.status == 20){ //待还
              item.num += item1.totalQty
          }else if(item.id == 25 && item1.status == 25){ //已还
              item.num += item1.totalQty
          }else if(item.id == 30 && item1.status == 30){ //已完成
              item.num += item1.totalQty
          }else if(item.id == 40 && item1.status == 40){ //待取消
              item.num += item1.totalQty
          }else if(item.id == 35 && item1.status == 35){ //已取消
              item.num += item1.totalQty
          }else if(item.id == 45 && item1.status == 45){ //已取消
              item.num += item1.totalQty
          }
      
        });
      });
    
    }
  })

}


// 重置
const handleReSet = () => {
  param.orderNo = null
  param.createDate = null
  param.planPickupDate = null
  param.payCurrency = null
  param.invoiceNo = null
  param.buyBoxCompanyName = null
  param.boxStartCity = null
  param.carryCityId = null
  param.currency = null
  getTableData()
}

//查看协议
const handleShowContract = (row: any) => {
  param.dialogContract = true
  const downloadUrl = JSON.parse(row.downloadUrl)
  param.contractUrl = downloadUrl.url
}

function handleClose() {
  getTableData()
  param.dialogVisible = false
}

//分页
function onTablePageChange(page) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

const tableRef = ref({ multipleSelection: [] })
const rowData = ref({})
const handleToRefund = (row: any) => {
  rowData.value = row
  param.dialogVisible = true
}

//
const showInfo = (row: any) => {
  // router.push('sellOrderInfo')
  orderInfo().setRowData(row)
  router.push({
    path: 'tradeOrder/details',
    query: {
      orderId: row.id,
      sourceType: 'edit',
      businessRoleEnum: 10  // 5:买箱 10：卖箱
    }
  })
}

// 城市id回写
const startCityId = (id: string) => {
  param.carryCityId = id
  param.boxStartCity = id
}
// const backCityId = (id: string) => {
//   param.boxBackCity = id
// }

const route = useRoute();

onActivated(() => {
  if(route.query.refNo){
    param.orderNo=route.query.refNo
  }
  getTableData()
})

const toExportBuyBoxPacking = () => { 
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  const ids = checkAllItem.map((item: any) => item.id)
    if (ids.length < 1) return ElMessage.warning('请选择需要导出的订单！')
    ElMessageBox.confirm('确认要导出选中的订单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        let reqParameters = {
          purchaseIds: ids
        }
        exportBoxPurchaseBoxOrder(reqParameters).then((res: any) => {
            downloadFile(res, '订单详情')
          
        }).catch((error) => {
            ElMessage.error(error)
        })
    }).catch(() => {
        // ElMessage.warning('请选择要收取的箱号！')
    })
}

//批量删除
const batchDelete = () => { 
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  const ids = checkAllItem.map((item: any) => item.id)
  ElMessageBox.confirm('确定要删除订单么？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteOrderByIds(ids).then((res: any) => { 
      if(res.code != '00000'){
        ElMessage.warning(res.msg)
      }else{
        getTableData()
        ElMessage.success('删除成功！')
      }
    })
  })
}
const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）

const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const slectAll = async(val:any) =>{
    checkAll.value = []
    let data = {
      pageNum: 1,
      pageSize: 10000,
      status: param.status || ''
    }
    await getSellPurchaseBoxOrderPage(data).then(res =>{ 
      if(res.code == "00000" && res.data.list && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}


</script>